package com.java.day13.homework;

import com.java.day08.feature.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 给定一个字符串,请输出该字符串由哪些字符组成,每个字符出现几次?
 */
public class homework01 {
    //遍历字符串
    //判断HashMap是否包含该字符
    //如果包含则出现次数+1
    //不包含则把其放入HashMap中
    public static void main(String[] args) {
        String s = "HelloWorld";
        String s1 = "I love java!!!";
        String s2 = "中文呢中不中?";

        HashMap<String, Integer> map = method(s);

        System.out.println(map);

        HashMap<String, Integer> map1 = method(s1);

        System.out.println(map1);

        HashMap<String, Integer> map2 = method(s2);

        System.out.println(map2);

    }

    public static HashMap<String, Integer> method(String s){
        //创建HashMap,key为字符,value为出现次数
        HashMap<String, Integer> map = new HashMap<>();

        //遍历字符串
        for (int i = 0; i < s.length(); i++) {
            //出现次数
            int count = 1;
            String c = String.valueOf(s.charAt(i));

            if(map.containsKey(c)){
                //出现次数+1,并覆盖
                count = map.get(c)+1;
                map.put(c,count);
            }else{
                map.put(c,count);
            }
        }
        return map;
    }

}
